package com.flower.controller;

import cn.hutool.core.collection.CollUtil;

import cn.hutool.core.date.DateUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.flower.model.entity.Out;
import com.flower.service.IOutService;
import com.flower.utils.DateUtils;
import cn.hutool.core.date.Quarter;
import com.flower.model.dto.SalePageQueryDTO;
import com.flower.model.entity.Customer;
import com.flower.model.entity.Sale;
import com.flower.result.PageResult;
import com.flower.result.Result;
import com.flower.result.SalePageResult;
import com.flower.service.CustomerService;
import com.flower.service.SaleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@SuppressWarnings("all")
/**
 *@ClassName SaleController
 *@Description TODO
 *@Author @O_o  GW__
 *@Date 2025/6/17 12:56
 *@Version 1.0
 */
@RestController
@Slf4j
@RequestMapping("/sale")
@Api(tags = "出库管理系统")
public class SaleController {
    @Autowired
    private SaleService saleService;
    @Autowired
    private IOutService outService;
    @GetMapping("/page1")
    @ApiOperation("分页查询出库单数据")
    public Result<PageResult> getSaleList(SalePageQueryDTO salePageQueryDTO) {
        PageResult pageResult = saleService.getSaleList(salePageQueryDTO);
        return Result.success(pageResult);
    }

    @PostMapping
    @ApiOperation("添加/编辑出库单")
    public Result<String> save(@RequestBody Sale sale) {
        log.info("添加/编辑出库单：{}", sale);
        saleService.addOrUpdate(sale);
        return Result.success("操作成功");
    }

    @DeleteMapping("/{id}")
    @ApiOperation("删除出库单")
    public Result<String> delete(@PathVariable Integer id) {
        log.info("删除出库单：{}", id);
        saleService.deleteSale(id);
        return Result.success("删除成功");
    }

    @PostMapping("del/batch")
    @ApiOperation("批量删除出库单")
    public Result<String> deleteList(@RequestBody List<Integer> ids) {
        log.info("批量删除出库单：{}", ids);
        saleService.deleteSaleList(ids);
        return Result.success("批量删除成功");
    }

    @GetMapping("/passsale")
    @ApiOperation("查询身份为销售员的用户")
    public Result<PageResult> getPassSale(@RequestParam Integer pageNum,
                                          @RequestParam Integer pageSize) {
        PageResult pageResult = saleService.getPassSale(pageNum, pageSize);
        return Result.success(pageResult);
    }

    @GetMapping("/sort")
    @ApiOperation("查询所有出库单")
    public Result members(){
        List<Out> list =outService.list();
        int q1=0;//第一季度
        int q2=0;//第二季度
        int q3=0;//第三季度
        int q4=0;//第四季度
        for (Out out : list){
            Date createTime=out.getOutDate();
            Quarter quarter= DateUtil.quarterEnum(createTime);
            switch (quarter){
                case Q1:q1 += 1; break;
                case Q2:q2 += 1; break;
                case Q3:q3 += 1; break;
                case Q4:q4 += 1; break;
                default: break;
            }
        }
        return Result.success(CollUtil.newArrayList(q1,q2,q3,q4));
    }
    /**
     * 导出接口
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response)throws Exception{
        //从数据库查询出所有的数据
        List<Sale> list = saleService.list();
        //通过工具类创建writer写出到磁盘路径
        //ExcelWriter writer = ExcelUtil.getWriter(filesUploadPath+ "/用户信息.xlsx");
        //在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //自定义标题别名
        writer.addHeaderAlias("id","编号");
        writer.addHeaderAlias("saleId","出库通知单编号");
        writer.addHeaderAlias("saler","申请人");
        writer.addHeaderAlias("saleDate","出库申请日期");
        writer.addHeaderAlias("saleName","出库产品名称");
        writer.addHeaderAlias("saleSupplier","供应商");
        writer.addHeaderAlias("saleNum","出库数量");
        writer.addHeaderAlias("saleUnit","数量单位");
        writer.addHeaderAlias("salePrice","单价");
        writer.addHeaderAlias("saleTotal","总价");
        writer.addHeaderAlias("salePaid","已付款");
        writer.addHeaderAlias("remarks","审核人备注");
        writer.addHeaderAlias("reviewer","审核人");
        writer.addHeaderAlias("results","审核结果");
        writer.addHeaderAlias("reviewdate","审核日期");
        writer.addHeaderAlias("applynote","申请人备注");



        //一次性写出list内的对象到Excel，使用默认样式，强制输出标题
        writer.write(list,true);
        //设置浏览器响应格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("出库通知单信息","UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out,true);
        out.close();
        writer.close();
    }

}
